import http from '@ohos.net.http';
import { preLoad, playAnimation } from '../../common/model/dynamicPlay'

function getDynamic(url, cb) {
    let lists = []
    let httpRequest = http.createHttp();
    httpRequest.request(
        url,
        {
            method: "GET", // 可选，默认为“GET”
            header: {
                'Content-Type': 'application/json'
            },
            readTimeout: 20000, // 可选，默认为60000ms
            connectTimeout: 20000 // 可选，默认为60000ms
        }, (err, data) => {
        if (!err) {
            console.info("xxx--- " + JSON.stringify(data))
            let res = JSON.parse(data.result)
            let list = res.result
            for (let i in list) {
                let img = new Image()
                img.src = list[i]
                lists.push(img)
            }
            let len = list.length
            cb(lists, len)
        } else {
            console.info('xxx--- error:' + JSON.stringify(err));
        }
    })
}

export function setDynamic(id, url, interval,ok,position, cb) {
    let width=720,height=1280,x=0,y=0
    if(position){
        width=position.width
        height=position.height
        x=position.x
        y=position.y
    }
    getDynamic(url, (lists, length) => {
        let info = {
            id: id,
            images: lists,
            length: length,
            interval: interval,
            width: width,
            height: height,
            x: x,
            y: y,
            ok: false,
            bitmap: []
        }
        console.info('xxx--- getDynamic suc '+info.length)
        if(ok){
            preLoad(info, (info) => {
                console.info('xxx--- preload finish')
                let player = new playAnimation(info);
                cb(player)
            })
        }else{
            let player = new playAnimation(info);
            cb(player)
        }

    })
}
